package com.moonbird.springboot.filter;

import com.alibaba.fastjson2.JSONObject;
import com.moonbird.springboot.DTO.Result;
import com.moonbird.springboot.Utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Enumeration;

/**
 * 登录校验过滤器
 * @author hpl
 */
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //System.out.println("拦截到了请求");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // 设置允许跨域访问的域名、方法和请求头
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, jwtToken");

        // 对于OPTIONS请求，直接返回状态200
        if ("OPTIONS".equalsIgnoreCase(req.getMethod())) {
            System.out.println("OPTIONS请求，直接返回200");
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        // 获取请求url
        String url = req.getRequestURI();

        if (!url.contains("actuator")){
            System.out.println("请求URL: " + url);
        }


        // 打印请求方法
        //System.out.println("请求方法: " + req.getMethod());

        // 打印请求路径
        //System.out.println("请求路径: " + req.getRequestURL());

        // 打印请求URI
        //System.out.println("请求URI: " + req.getRequestURI());

        // 打印Servlet路径
        //System.out.println("Servlet路径: " + req.getServletPath());

        // 判断url是否包含了login
        //"/login"
        if (url.contains("/login") || url.contains("/register") || url.contains("/actuator")) {
            // 放行
            //System.out.println("请求包含 /login，放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 获取请求头当中的令牌
        String jwt = req.getHeader("jwttoken");
        //System.out.println("jwttoken: " + jwt);

        // 获取所有请求头
//        Enumeration<String> headerNames = req.getHeaderNames();
//        while (headerNames.hasMoreElements()) {
//            String headerName = headerNames.nextElement();
//            String headerValue = req.getHeader(headerName);
//            System.out.println(headerName + ": " + headerValue);
//
//        }

        System.out.println("===============================================================");
        // 判断令牌是否存在
        if (!StringUtils.hasLength(jwt)) {
            System.out.println("jwttoken为空，未登录");
            Result error = Result.fail(5000,"NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            System.out.println(notLogin);
            resp.getWriter().write(notLogin);
            return;
        }

        // 校验jwt令牌
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("解析jwt失败，未登录");
            Result error = Result.fail(5000,"NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }

        // 令牌合法，放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
